/*
 * @Descripttion: 胡腾辉 | feico
 * @version: V1.0
 * @Author: feico
 * @Date: 2022-02-20 12:02:08
 * @LastEditors: feico
 * @LastEditTime: 2022-02-22 15:43:51
 */
import axios from 'axios'
import { getToken } from '.'
import {message} from 'antd'
import store from '../store'
import { logout } from '../store/action/login'
import history from '../utils/history'
import { userInfoAc } from '../store/action/user'
const instance = axios.create({
    baseURL: 'http://geek.itheima.net/v1_0/',
    timeout: 5000,
})
// 添加请求拦截器
instance.interceptors.request.use(
    (config) => {
       // 在发送请求之前做些什么
    if (getToken()) {
        config.headers.Authorization = `Bearer ${getToken()}`
      }
      return config
    },
    (error) => {
        // 对请求错误做些什么
        return Promise.reject(error)
    }
)

// 添加响应拦截器
instance.interceptors.response.use(
    (response) => {
        // 对响应数据做点什么
        return response
    },
    (error) => {
        // 弱网
        if (!error.response) return message.error('网络太弱了')
        if (error.response.status === 401) {
          store.dispatch(logout())
          store.dispatch(userInfoAc({})) // 清除用户信息
          history.replace({
              pathname:'/login',
              state:{from:history.location.pathname}
          }) 
          message.info('退出成功', 1)
        }
        // 对响应错误做点什么
        return Promise.reject(error)
      }
)

export default instance